import { rmdir_recursive } from './utils.js';
import { android_get_app_list } from "./device_manager_android.js"
import {
    openharmony_get_app_list,
    openharmony_start_app,
    openharmony_start_collect,
    openharmony_stop_collect } from "./device_manager_openharmony.js"

const fs = window.require('fs');

let g_app_path = '';
let g_tool_path = '';
let g_dev_id = '';

export function device_manager_init(app_path, dev_tool, dev_id) {
    g_app_path = app_path;
    g_tool_path = app_path + '\\plugins\\' + dev_tool;
    g_dev_id = dev_id;
}

export function get_app_list() {
    if (g_tool_path.endsWith('hdc')) {
        return openharmony_get_app_list(g_tool_path, g_dev_id);
    }

    if (g_tool_path.endsWith('adb')) {
        return android_get_app_list(g_tool_path, g_dev_id);
    }

    return [];
}

export function start_app(package_name) {
    if (g_tool_path.endsWith('hdc')) {
        return openharmony_start_app(package_name, g_tool_path, g_dev_id);
    }

    return -1;
}

export function start_collect(package_name, data_mask) {
    if (g_tool_path.endsWith('hdc')) {
        return openharmony_start_collect(package_name, g_tool_path, g_dev_id, data_mask);
    }

    return -1;
}

export function stop_collect(report_name) {
    let report_path = '';
    if (report_name.length > 0) {
        report_path = g_app_path + '\\src\\pages\\game\\report\\' + report_name;

        try {
            fs.accessSync(report_path, fs.constants.R_OK);
            if (rmdir_recursive(report_path) < 0) {
                return -1;
            }
        } catch(err) {}

        try {
            fs.mkdirSync(report_path);
        } catch(err) {
            console.log(err);
            return -1;
        }
    }

    if (g_tool_path.endsWith('hdc')) {
        return openharmony_stop_collect(g_tool_path, g_dev_id, report_path);
    }

    return -1;
}